#!/bin/bash
# buildlinux - Build a fully functional Linux system.
# http://code.google.com/p/buildlinux/
# Licensed under the GPL v3
# TODO: Clean Up this mess :)
VERSION="0.1"
DIALOG='zenity'

# Download URLs
# All URL's taken from the Linux from Scratch book
# http://www.linuxfromscratch.org/

MainMenu()
{
	MENUOPTION=$($DIALOG --list --text "Select an option:" --radiolist --width 0 --height 0 --column "Pick" --column "Option"  \
	TRUE "Create System" \
	FALSE "Download Sources" \
	FALSE "Download Patches" \
	FALSE "Build Sources" \
	FALSE "Build System Image" \
	FALSE "Exit" )

	case $MENUOPTION in
		"Create System") CreateSystem;;
		"Download Sources") DownloadSources;;
		"Download Patches") DownloadPatches;;
		"Build Sources") echo "Build Sources";;
		"Build System Image") echo "Build System Image";;
		"Exit") break;;
	esac
}

DownloadSources()
{
	# TODO: Close progressbar and kill the script
	SetSourceDir
	# Get linklist.txt from server
	if [ -f linklist.txt ]; then
		$DIALOG --title="Linklist" --info "Old linklist found; downloading updated one." 0 0
		wget -O linklist.txt http://buildlinux.googlecode.com/svn/trunk/linklist.txt 2>&1 | sed -u 's/.*\ \([0-9]\+%\)\ \+\([0-9.]\+\ [KMB\/s]\+\)$/\1\n# Downloading \2/' | zenity --progress --title="Downloading File..." --auto-close 2> /dev/null 
		echo "Linklist downloaded"
		sleep 2
	else
		echo "Downloading linklist"
		wget -O linklist.txt http://buildlinux.googlecode.com/svn/trunk/linklist.txt 2>&1 | sed -u 's/.*\ \([0-9]\+%\)\ \+\([0-9.]\+\ [KMB\/s]\+\)$/\1\n# Downloading \2/' | zenity --progress --title="Downloading File..." --auto-close 2> /dev/null
		echo "Linklist downloaded"
		sleep 2
	fi
	# Download sources
	echo "Downloading sources. This can take several minutes."
	sleep 2
	while read line; do
		wget --progress=bar:force $line -O/dev/null 2>&1 | zenity --title="Downloading Sources..." --progress --auto-close --auto-kill --text=$line
	done < linklist.txt
	zenity --warning --text "Sources downloaded.";
}

CreateSystem()
{
	SetWorkDir
	DownloadSources
}

SetWorkDir()
{
	WORKDIR=$(zenity --file-selection --directory --title="Select a directory for the system files.")
	mkdir $WORKDIR/sources
	mkdir $WORKDIR/mnt
	cd $WORKDIR
}

SetSourceDir()
{
	SRCDIR=$(zenity --file-selection --directory --title="Select a directory for the source files.")
	cd $SRCDIR
}

DownloadPatches()
{
	# Placeholder
}

MainMenu
echo $MENUOPTION
